package win.larryzeal.concurrent;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * Created by 张少昆 on 2017/9/23.
 */
public class SemaphoreDemo {


    public static void main(String[] args){
        final Semaphore semaphore = new Semaphore(2);
        ExecutorService executorService = Executors.newCachedThreadPool();
        for(int i = 0; i < 20; i++){
            executorService.submit(new MyRunnable(semaphore, i));
        }
        executorService.shutdown();
    }

    static class MyRunnable implements Runnable {
        private Semaphore semaphore;
        private int user;

        public MyRunnable(Semaphore semaphore, int user){
            this.semaphore = semaphore;
            this.user = user;
        }

        @Override
        public void run(){
            try{
                semaphore.acquire();
                System.out.println("user [" + user + "] come");
                Thread.sleep((long) (Math.random() * 10 * 1000));
                System.out.println("user [" + user + "] is to buy ticket");
                Thread.sleep((long) (Math.random() * 10 * 1000));
                System.out.println("user [" + user + "] is to leave");

                semaphore.release();
            } catch(InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}
